/*
 * @Author: xiaozhuang-c-language 3535851673@qq.com
 * @Date: 2025-10-12 14:37:29
 * @LastEditors: xiaozhuang-c-language 3535851673@qq.com
 * @LastEditTime: 2025-10-12 15:16:27
 * @FilePath: /zhuang/linux-study/mmapTest/write.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <cstddef>
#include <sys/mman.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
#define PAGESIZE 4096
// ./exe filename
int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    std::cout << "Usage: " << argv[0] << "filename " << std::endl;
    return 1;
  }
  //1.打开目标文件：mmap需要你自己先打开文件
  int fd = ::open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
  if(fd < 0)
  {
    std::cout << "Failed to open file" << argv[1] << std::endl;
    return 2;
  }
  //2.手动调整文件大小为page
  if(::ftruncate(fd,PAGESIZE) == -1)
  {
    std::cout << "Failed to truncate size :" << argv[1] << std::endl;
    return 3;
  }
  //3.进行共享映射
  char* addr = (char*)mmap(nullptr,PAGESIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  if(addr == MAP_FAILED)
  {
    std::cout << "Failed to mmap file :" << argv[1] << std::endl;
    return 4;
  }
 
  //4.进行文件操作,采用操作内存的方式操作文件
  for(auto ch = 'a' ; ch <= 'z';ch++)
  {
     addr[ch-'a'] = ch;
     sleep(1);
  }
  //5.关闭文件映射
  if(::munmap(addr, PAGESIZE) == -1)
  {
        std::cout << "Failed to munmap file:" << argv[1] << std::endl;
        return 5;
  }
  
  ::close(fd);

}




